package com.liujit.gateway.filter;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.liujit.common.domain.result.Result;
import com.liujit.gateway.constants.FilterOrderConstant;
import com.liujit.gateway.constants.GateWayConstant;
import com.liujit.gateway.domain.SysLog;
import com.liujit.gateway.properties.SysLogProperties;
import com.liujit.gateway.utils.LogUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.Objects;

/**
 * @Description: 响应日志打印
 * @Author: liujun
 * @Date: 2021/6/30 10:31 下午
 */
@RequiredArgsConstructor
@Slf4j
@Component
@EnableConfigurationProperties(SysLogProperties.class)
public class ResponseLogFilter implements GlobalFilter, Ordered {

    private final WebClient webClient;

    private final SysLogProperties sysLogProperties;

    @Override
    public int getOrder() {
        return FilterOrderConstant.RESPONSE_LOG_FILTER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 白名单
        if (exchange.getAttribute(GateWayConstant.IGNORE_URL)) {
            return chain.filter(exchange);
        }
        // 获取日志
        SysLog sysLog = exchange.getAttribute(GateWayConstant.SYS_LOG);
        sysLog.setRespTime(new Date());
        sysLog.setUseTime(DateUtil.between(sysLog.getReqTime(), sysLog.getRespTime(), DateUnit.MS));
        ServerHttpResponse response = exchange.getResponse();
        DataBufferFactory bufferFactory = response.bufferFactory();
        ServerHttpResponseDecorator decorator = new ServerHttpResponseDecorator(response) {

            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                    return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                        DataBuffer join = bufferFactory.join(dataBuffers);
                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        DataBufferUtils.release(join);
                        String responseBody;
                        MediaType contentType = response.getHeaders().getContentType();
                        // 下载文件时 不需要打印具体响应内容 标识即可
                        if (Objects.nonNull(contentType) && LogUtil.isUploadFile(contentType)) {
                            responseBody = "下载文件";
                        } else {
                            Charset charset = LogUtil.getCharset(contentType);
                            responseBody = new String(content, charset);
                        }
                        // 转换对象
                        Result result = JSONUtil.toBean(responseBody, Result.class);
                        sysLog.setRespCode(result.getCode());
                        sysLog.setRespMsg(result.getMsg());
                        sysLog.setRespData(JSONUtil.toJsonStr(result.getData()));
                        saveLog(sysLog);
                        return bufferFactory.wrap(content);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decorator).build());
    }

    private void saveLog(SysLog sysLog) {
        webClient.post().uri(sysLogProperties.getAddUrl()).body(Mono.just(sysLog), SysLog.class).retrieve()
                .bodyToMono(Result.class).onErrorResume(WebClientResponseException.class, err -> {
            log.error("保存日志err:{}，保存内容:{}", err, JSONUtil.toJsonStr(sysLog));
            return Mono.empty();
        }).subscribe();
    }
}
